package com.campsys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.campsys.entity.Course;
import com.campsys.entity.TeachingUnit;
import com.campsys.entity.LearningRecord;
import com.campsys.mapper.CourseMapper;
import com.campsys.mapper.TeachingUnitMapper;
import com.campsys.mapper.LearningRecordMapper;
import com.campsys.service.TeachingUnitService;
import com.campsys.service.dto.TeachingUnitDTO;
import com.campsys.service.dto.TeachingUnitQueryDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
@Slf4j
public class TeachingUnitServiceImpl implements TeachingUnitService {
    
    @Autowired
    private CourseMapper courseMapper;
    
    @Autowired
    private TeachingUnitMapper unitMapper;
    
    @Autowired
    private LearningRecordMapper recordMapper;
    
    @Override
    public IPage<TeachingUnit> getUnitList(Page<TeachingUnit> page, TeachingUnitQueryDTO queryDTO, Long teacherId) {
        // 验证课程所有权
        validateCourseOwnership(queryDTO.getCourseId(), teacherId);
        
        LambdaQueryWrapper<TeachingUnit> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TeachingUnit::getCourseId, queryDTO.getCourseId());
        
        // 添加查询条件
        if (queryDTO.getParentId() != null) {
            wrapper.eq(TeachingUnit::getParentId, queryDTO.getParentId());
        }
        if (StringUtils.isNotBlank(queryDTO.getTitle())) {
            wrapper.like(TeachingUnit::getTitle, queryDTO.getTitle());
        }
        if (queryDTO.getType() != null) {
            wrapper.eq(TeachingUnit::getType, queryDTO.getType());
        }
        if (queryDTO.getStatus() != null) {
            wrapper.eq(TeachingUnit::getStatus, queryDTO.getStatus());
        }
        
        wrapper.orderByAsc(TeachingUnit::getSort);
        return unitMapper.selectPage(page, wrapper);
    }
    
    @Override
    @Transactional
    public void addUnit(TeachingUnitDTO unitDTO, Long teacherId) {
        // 验证课程所有权
        validateCourseOwnership(unitDTO.getCourseId(), teacherId);
        
        // 如果是小节，验证父章是否存在且属于同一课程
        if (unitDTO.getType() == 2) {
            TeachingUnit parent = unitMapper.selectById(unitDTO.getParentId());
            if (parent == null || !parent.getCourseId().equals(unitDTO.getCourseId())) {
                throw new IllegalArgumentException("父章节不存在或不属于该课程");
            }
        }
        
        TeachingUnit unit = new TeachingUnit();
        BeanUtils.copyProperties(unitDTO, unit);
        
        unit.setCreateTime(LocalDateTime.now());
        unit.setCreateBy(teacherId.toString());
        
        unitMapper.insert(unit);
    }
    
    @Override
    @Transactional
    public void updateUnit(TeachingUnitDTO unitDTO, Long teacherId) {
        // 验证单元是否存在且属于该教师的课程
        TeachingUnit existingUnit = validateUnitOwnership(unitDTO.getId(), teacherId);
        
        TeachingUnit unit = new TeachingUnit();
        BeanUtils.copyProperties(unitDTO, unit);
        
        unit.setCourseId(existingUnit.getCourseId());  // 确保课程ID不变
        unit.setUpdateTime(LocalDateTime.now());
        unit.setUpdateBy(teacherId.toString());
        
        unitMapper.updateById(unit);
    }
    
    @Override
    @Transactional
    public void deleteUnit(Long id, Long teacherId) {
        // 验证单元是否存在且属于该教师的课程
        TeachingUnit unit = validateUnitOwnership(id, teacherId);
        
        // 如果是章节，检查是否有小节
        if (unit.getType() == 1) {
            LambdaQueryWrapper<TeachingUnit> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TeachingUnit::getParentId, id);
            if (unitMapper.selectCount(wrapper) > 0) {
                throw new IllegalArgumentException("该章节下有小节，无法删除");
            }
        }
        
        // 检查是否有学习记录
        LambdaQueryWrapper<LearningRecord> recordWrapper = new LambdaQueryWrapper<>();
        recordWrapper.eq(LearningRecord::getUnitId, id);
        if (recordMapper.selectCount(recordWrapper) > 0) {
            throw new IllegalArgumentException("该单元已有学习记录，无法删除");
        }
        
        unitMapper.deleteById(id);
    }
    
    @Override
    @Transactional
    public void updateStatus(Long id, Integer status, Long teacherId) {
        if (status != 0 && status != 1) {
            throw new IllegalArgumentException("无效的状态值");
        }
        
        // 验证单元是否存在且属于该教师的课程
        TeachingUnit unit = validateUnitOwnership(id, teacherId);
        
        // 如果是章节，同时更新所有小节状态
        if (unit.getType() == 1) {
            LambdaQueryWrapper<TeachingUnit> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TeachingUnit::getParentId, id);
            
            TeachingUnit updateUnit = new TeachingUnit();
            updateUnit.setStatus(status);
            updateUnit.setUpdateTime(LocalDateTime.now());
            updateUnit.setUpdateBy(teacherId.toString());
            
            unitMapper.update(updateUnit, wrapper);
        }
        
        // 更新当前单元状态
        TeachingUnit updateUnit = new TeachingUnit();
        updateUnit.setId(id);
        updateUnit.setStatus(status);
        updateUnit.setUpdateTime(LocalDateTime.now());
        updateUnit.setUpdateBy(teacherId.toString());
        
        unitMapper.updateById(updateUnit);
    }
    
    @Override
    public IPage<LearningRecord> getUnitLearningRecords(Page<LearningRecord> page, Long unitId, Long teacherId) {
        // 验证单元是否存在且属于该教师的课程
        validateUnitOwnership(unitId, teacherId);
        
        LambdaQueryWrapper<LearningRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LearningRecord::getUnitId, unitId);
        wrapper.orderByDesc(LearningRecord::getStartTime);
        
        return recordMapper.selectPage(page, wrapper);
    }
    
    private Course validateCourseOwnership(Long courseId, Long teacherId) {
        Course course = courseMapper.selectById(courseId);
        if (course == null) {
            throw new IllegalArgumentException("课程不存在");
        }
        if (!course.getTeacherId().equals(teacherId)) {
            throw new IllegalArgumentException("无权操作此课程");
        }
        return course;
    }
    
    private TeachingUnit validateUnitOwnership(Long unitId, Long teacherId) {
        TeachingUnit unit = unitMapper.selectById(unitId);
        if (unit == null) {
            throw new IllegalArgumentException("教学单元不存在");
        }
        validateCourseOwnership(unit.getCourseId(), teacherId);
        return unit;
    }
} 